public without sharing class MeasureCalcHandler {

    ///在测算审批通过的时候  将通过的的测算设为有效,将之前有效的测算改为无效
   public static void changeStaus(List<Measure_Calculate__c> newList, Map<Id,Measure_Calculate__c> oldMap) {
        Map<Id,Measure_Calculate__c> mcMap = new Map<Id,Measure_Calculate__c>();
//System.debug('更新之前' + newList);
        Id rtId = Utils.getRecordTypeIdByDevNameAndObjName('StandardCalculation', 'Measure_Calculate__c');
        Map<String,String> oppMap = new Map<String,String>(); 
        for (Measure_Calculate__c mc : newList) {
            
           Measure_Calculate__c oldmc = oldMap.get(mc.Id);
           System.debug(oldmc);

           if( mc.RecordTypeId == rtId &&  mc.Status__c == '审批中(销售主管已批准)' && oldmc.Status__c != mc.Status__c && (mc.SaleAmountRatio__c == null || mc.OneTimeSaleAmount__c == null )){

              mc.addError('业务费用比例和开发费用不能为空，如无，可填写为“0”，请点击按钮“修改测算”如实填写，否则无法审批!');

              return;
           }
            //如果是审批通过 则设为有效
            if ( mc.Status__c != oldmc.Status__c && mc.Status__c == '审批成功' ) {



                mc.IsActive__c = true;
                
                List<Measure_Calculate__c>  mcList= new List<Measure_Calculate__c> ();
                for ( Measure_Calculate__c other: [select Id,Status__c from Measure_Calculate__c where Opportunity__c =:mc.Opportunity__c and IsActive__c = true ]) {
                  if(other.Id != mc.Id ){
                    other.IsActive__c = false;
                    mcList.add(other);
                  }
                }
                Opportunity opp = new Opportunity(Id=mc.Opportunity__c,ActiveMeasureReagent__c = mc.Id);
                if(mcList.size()>0) update mcList;
                update opp;
              //  System.debug('更新的'+mc);
            }
        }
        



   }
   public static void calcZc(Map<Id,Measure_Calculate__c> qM ){
        

        Map<Id,String> tMap = new Map<Id,String>();
        Map<Id,Set<Id>> mMap = new Map<Id,Set<Id>>();

        for (Measure_Calculate__c q : qM.values() ) {
           
           Set<Id> m = mMap.containsKey(q.Opportunity__c ) ? mMap.get(q.Opportunity__c) : new Set<Id>();
           m.add(q.Id );
           mMap.put(q.Opportunity__c, m );

        }
        Set<String> companys = new Set<String>();
        Set<String> provinces = new Set<String>();
        Map<String,String> mProvinces= new Map<String,String>();
        for (Opportunity opp : [select Id ,AccountId,Account.InstCompany__c  from Opportunity where Id in: mMap.keySet() ] ) {
           String company = opp.Account.InstCompany__c == null ? 'MKSW' : opp.Account.InstCompany__c; 
          String province = CompanyProvinceUtil.getCompanyCodeAndProvince(company).get(0) ;
          company = CompanyProvinceUtil.transCodeToName(company);
            companys.add(company );
            provinces.add( province);

            mProvinces.put(opp.Id , company+province);
            
        }

        Set<Id> pids = new Set<Id>();
        List<Measure_Calculate_Product__c> qpList  =[select Measure_Calculate__r.Opportunity__c , Measure_Calculate__c,Quantity__c,Product__c,Product__r.Brand__c,Product__r.NCCode__c,Product__r.Category1__c,Product__r.Category0__c  from Measure_Calculate_Product__c where Measure_Calculate__c in:qM.keySet()  ];
       
       for(Measure_Calculate_Product__c qp :  qpList ){

            String type  = tMap.get(qp.Measure_Calculate__c);
             if( MaccuraBrandUtil.maccura.contains(qp.Product__r.Brand__c) || MaccuraBrandUtil.maccura.contains(qp.Product__r.NCCode__c) || (qp.Product__r.Category1__c == '生化' &&  qp.Product__r.Category0__c == '仪器' )) {
                if( qp.Product__r.Category0__c == '仪器' )pids.add(qp.Product__c);
               
                type = (type == null ||  !type.contains('非自产') ) ? '自产' :'自产/非自产';
                  
             }else{

                 type = ( type == null || type == '非自产'   ) ? '非自产' :'自产/非自产';

             }
            tMap.put(qp.Measure_Calculate__c, type);
       }

      Map<String ,Decimal> priceMap = new Map<String,Decimal>();
       for (Price__c p :[select Id,Product__c,Company__c ,Province__c ,InstCost__c from Price__c where Product__c in: pids and Company__c in : companys and Province__c in: provinces and ClosePrice__c != true ] ) {
          priceMap.put(p.Product__c+p.Company__c+p.Province__c, p.InstCost__c);
       }

       
       Map<String,Decimal> mT = new Map<String ,Decimal>();
       for(Measure_Calculate_Product__c qp :  qpList ){

          if( MaccuraBrandUtil.maccura.contains(qp.Product__r.Brand__c) || MaccuraBrandUtil.maccura.contains(qp.Product__r.NCCode__c) || (qp.Product__r.Category1__c == '生化' &&  qp.Product__r.Category0__c == '仪器' )) {
               Decimal t =  mT.containsKey(qp.Measure_Calculate__c)  ? mT.get(qp.Measure_Calculate__c) : 0;
               String key = qp.Product__c+ mProvinces.get(qp.Measure_Calculate__r.Opportunity__c );
               
               t+= (priceMap.get(key) == null ? 0 :priceMap.get(key)) * (qp.Quantity__c == null ? 0 : qp.Quantity__c );
              mT.put(qp.Measure_Calculate__c,t);
          }
       }


       for ( Measure_Calculate__c q : qM.values() ) {
           
           q.ZC__c = tMap.get(q.Id);
           q.SelfProductionCostCount__c = mt.get(q.Id );


       }


      



    }
   ///审批通过后重新计算 业务机会 的项目类型
      /*
        
   public static void setOppProjectTypewhenUpate(List<Measure_Calculate__c> newList) {
        Set<Id>  opps= new Set<Id>();
        ///审批成功 且有效的测算
        for (Measure_Calculate__c mc : newList) {
          if(mc.Status__c == '已提交' || mc.Status__c == '审批成功' || mc.Status__c == '审批拒绝')  opps.add(mc.Opportunity__c);
        }
        if (opps.size() > 0) OppSetProjectTypeHandler.calcOppSetProjectType(opps);
      


   }
   */
   ///改变业务机会的状态
     public static void setOppStageName(List<Measure_Calculate__c> newList, Map<Id, Measure_Calculate__c> oldMap) {
        for (Measure_Calculate__c mc: newList) {
            Measure_Calculate__c oldmc = oldMap.get(mc.Id);
            if (oldmc.Status__c != mc.Status__c && mc.Status__c == '已提交') {
                // FIXME 审批只会一条一条来，所以允许在for循环里面写soql
                Opportunity opp = [select Id, RecordType.Name, StageName,ExecuteCompany__r.RecordType.DeveloperName from Opportunity where Id = :mc.Opportunity__c];
                // if (opp.ExecuteCompany__r.RecordType.DeveloperName == 'Maccura') {
               if(opp.StageName == '立项' ){
                  opp.StageName = '方案谈判';
                  update opp;
               } 
            }
        }
    }

}